'use client'

import { useState, useEffect } from 'react'
import { Card } from '../ui/Card'
import { DeviceIcon } from '../icons/DeviceIcon'
import { PowerIcon, Sliders, Trash2, MoreVertical, Lock } from 'lucide-react'
import { DEVICE_TYPES } from '@/constants/deviceTypes'

interface DeviceCardProps {
  device: {
    id: string
    name: string
    type: string
    status: boolean
    data: {
      power?: number
      temperature?: number
      brightness?: number
      position?: number
      volume?: number
      playing?: boolean
      locked?: boolean
    }
  }
  onToggle: () => void
  onDelete: () => void
  onUpdateData: (data: Record<string, number>) => void
}

export default function DeviceCard({ device, onToggle, onDelete, onUpdateData }: DeviceCardProps) {
  const [showMenu, setShowMenu] = useState(false)
  const deviceType = DEVICE_TYPES[device.type as keyof typeof DEVICE_TYPES]

  const handleClickOutside = () => {
    setShowMenu(false)
  }

  useEffect(() => {
    if (showMenu) {
      document.addEventListener('click', handleClickOutside)
    }
    return () => {
      document.removeEventListener('click', handleClickOutside)
    }
  }, [showMenu])

  const renderSlider = (value: number, onChange: (value: number) => void, disabled: boolean = false) => (
    <div className="relative h-2 bg-white/5 rounded-lg">
      {/* 滑块控制 */}
      <input
        type="range"
        min="0"
        max="100"
        disabled={disabled}
        value={value}
        onChange={(e) => onChange(Number(e.target.value))}
        className="absolute inset-0 w-full h-full appearance-none cursor-pointer
                 [&::-webkit-slider-runnable-track]:bg-transparent
                 [&::-webkit-slider-thumb]:appearance-none
                 [&::-webkit-slider-thumb]:w-4
                 [&::-webkit-slider-thumb]:h-4
                 [&::-webkit-slider-thumb]:bg-white
                 [&::-webkit-slider-thumb]:rounded-full
                 [&::-webkit-slider-thumb]:border-2
                 [&::-webkit-slider-thumb]:border-primary-500
                 [&::-webkit-slider-thumb]:shadow-lg
                 [&::-webkit-slider-thumb]:shadow-primary-500/50
                 [&::-webkit-slider-thumb]:cursor-pointer
                 [&::-webkit-slider-thumb]:transition-transform
                 [&::-webkit-slider-thumb]:hover:scale-110
                 [&::-webkit-slider-thumb]:hover:border-primary-400
                 [&::-moz-range-track]:bg-transparent
                 [&::-moz-range-thumb]:appearance-none
                 [&::-moz-range-thumb]:w-4
                 [&::-moz-range-thumb]:h-4
                 [&::-moz-range-thumb]:bg-white
                 [&::-moz-range-thumb]:rounded-full
                 [&::-moz-range-thumb]:border-2
                 [&::-moz-range-thumb]:border-primary-500
                 [&::-moz-range-thumb]:shadow-lg
                 [&::-moz-range-thumb]:shadow-primary-500/50
                 [&::-moz-range-thumb]:cursor-pointer
                 disabled:opacity-50"
        style={{
          background: `linear-gradient(to right, 
            rgb(59, 130, 246) 0%, 
            rgb(59, 130, 246) ${value}%, 
            transparent ${value}%, 
            transparent 100%)`
        }}
      />
    </div>
  )

  const renderControls = () => {
    const isDisabled = !device.status
    const disabledClass = isDisabled ? 'opacity-50 pointer-events-none' : ''

    switch (device.type) {
      case 'SPEAKER':
        return (
          <div>
            <div className="flex items-center space-x-4">
              {/* 音量控制 */}
              <div className="flex-1">
                <div className="flex justify-between mb-2">
                  <span className="text-sm font-medium text-white/70">音量</span>
                  <span className="text-sm text-white/60">{device.data.volume || 0}%</span>
                </div>
                {renderSlider(
                  device.data.volume || 0,
                  (value) => onUpdateData({ volume: value }),
                  !device.status
                )}
              </div>

              {/* 播放控制按钮 */}
              <button
                disabled={!device.status}
                onClick={() => onUpdateData({ playing: device.data.playing ? 0 : 1 })}
                className={`h-10 px-4 rounded-lg transition-colors flex items-center justify-center
                  ${device.data.playing 
                    ? 'bg-green-500/20 text-green-300 hover:bg-green-500/30' 
                    : 'bg-red-500/20 text-red-300 hover:bg-red-500/30'}
                  disabled:opacity-50 disabled:cursor-not-allowed`}
              >
                <span>{device.data.playing ? '暂停' : '播放'}</span>
              </button>
            </div>
          </div>
        )

      case 'LIGHT':
        return (
          <div>
            <div className="flex justify-between mb-2">
              <span className="text-sm font-medium text-white/70">亮度</span>
              <span className="text-sm text-white/60">{device.data.brightness || 0}%</span>
            </div>
            {renderSlider(
              device.data.brightness || 0,
              (value) => onUpdateData({ brightness: value }),
              !device.status
            )}
          </div>
        )

      case 'AC':
        return (
          <div className="space-y-4">
            <div className="flex items-center justify-between">
              <span className="text-sm text-white/70">温度</span>
              <div className="flex items-center space-x-2">
                <button
                  onClick={() => onUpdateData({ temperature: (device.data.temperature || 25) - 1 })}
                  className="w-8 h-8 rounded-full bg-white/5 hover:bg-white/10 flex items-center justify-center"
                >
                  -
                </button>
                <span className="text-lg text-white/80 w-12 text-center">
                  {device.data.temperature}°C
                </span>
                <button
                  onClick={() => onUpdateData({ temperature: (device.data.temperature || 25) + 1 })}
                  className="w-8 h-8 rounded-full bg-white/5 hover:bg-white/10 flex items-center justify-center"
                >
                  +
                </button>
              </div>
            </div>
          </div>
        )

      case 'CURTAIN':
        return (
          <div>
            <div className="flex justify-between mb-2">
              <span className="text-sm font-medium text-white/70">开合度</span>
              <span className="text-sm text-white/60">{device.data.position || 0}%</span>
            </div>
            {renderSlider(
              device.data.position || 0,
              (value) => onUpdateData({ position: value }),
              !device.status
            )}
          </div>
        )

      case 'LOCK':
        return (
          <div>
            {/* 使用 flex 布局将状态和控制按钮放在同一行 */}
            <div className="flex items-center space-x-4">
              {/* 状态显示 */}
              <div className="flex-1">
                <div className="flex justify-between items-center">
                  <span className="text-sm font-medium text-white/70">当前状态</span>
                  <span className={`text-sm ${device.data.locked ? 'text-green-400' : 'text-red-400'}`}>
                    {device.data.locked ? '已上锁' : '已解锁'}
                  </span>
                </div>
              </div>

              {/* 控制按钮 */}
              <button
                disabled={!device.status}
                onClick={() => onUpdateData({ locked: device.data.locked ? 0 : 1 })}
                className={`h-10 px-4 rounded-lg transition-colors flex items-center justify-center space-x-2
                  ${device.data.locked 
                    ? 'bg-green-500/20 text-green-300 hover:bg-green-500/30' 
                    : 'bg-red-500/20 text-red-300 hover:bg-red-500/30'}
                  disabled:opacity-50 disabled:cursor-not-allowed`}
              >
                <Lock className="w-4 h-4" />
                <span>{device.data.locked ? '解锁' : '上锁'}</span>
              </button>
            </div>
          </div>
        )

      default:
        return null
    }
  }

  return (
    <Card>
      <div className="h-[369px] relative flex flex-col">
        <div className="absolute top-3 right-3">
          <div className={`
            w-3 h-3 rounded-full
            ${device.status ? 'bg-green-400' : 'bg-red-400'}
            shadow-lg shadow-current
            animate-pulse
          `} />
        </div>

        <div className="p-6 flex-1 ">
          <div className="mb-8">
            <div className="w-16 h-16 rounded-full bg-primary-500/20 flex items-center justify-center mb-4">
              <DeviceIcon type={device.type} className="w-8 h-8 text-primary-400" />
            </div>
            <h3 className="text-xl font-medium text-white">{device.name}</h3>
            <p className="text-sm text-white/60 mt-1">{deviceType?.name || device.type}</p>
            {deviceType?.description && (
              <p className="text-xs text-white/40 mt-1">{deviceType.description}</p>
            )}
          </div>

          <div className="space-y-6">
            <div className="pt-4 border-t border-white/10">
              {renderControls()}
            </div>
          </div>
        </div>

        <div className="flex-none p-6 pt-4 border-t border-white/10">
          <div className="flex items-center space-x-2">
            <button
              onClick={onToggle}
              className={`flex-1 h-10 px-3 rounded-lg transition-colors flex items-center justify-center space-x-2
                ${device.status 
                  ? 'bg-green-500/20 text-green-300 hover:bg-green-500/30' 
                  : 'bg-red-500/20 text-red-300 hover:bg-red-500/30'}`}
            >
              <PowerIcon className="w-4 h-4" />
              <span>{device.status ? '开启' : '关闭'}</span>
            </button>
            
            <div className="relative">
              <button
                onClick={(e) => {
                  e.stopPropagation()
                  setShowMenu(!showMenu)
                }}
                className="h-10 w-10 rounded-lg bg-white/5 text-white/40 hover:bg-white/10 hover:text-white/60 transition-colors flex items-center justify-center"
              >
                <MoreVertical className="w-4 h-4" />
              </button>
              
              {showMenu && (
                <div className="absolute bottom-full right-0 mb-2 w-32 py-1 bg-background-paper rounded-lg border border-white/10 shadow-xl">
                  <button
                    onClick={(e) => {
                      e.stopPropagation()
                      if (confirm('确定要删除此设备吗？')) {
                        onDelete()
                      }
                      setShowMenu(false)
                    }}
                    className="w-full px-4 py-2 text-sm text-left text-red-400 hover:bg-white/5 flex items-center space-x-2"
                  >
                    <Trash2 className="w-4 h-4" />
                    <span>删除设备</span>
                  </button>
                </div>
              )}
            </div>
          </div>
        </div>
      </div>
    </Card>
  )
} 